<template>
  <div class="bg-fixed"></div>
  <el-container class="register-container">
    <el-header class="title">基于GAP的农产品质量安全全程智能系统</el-header>
    <el-main>
      <div class="box">
        <el-form ref="formRef" :model="form" :rules="rules" class="w-[250px]">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon>
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password>
              <template #prefix>
                <el-icon>
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="form.conpassword" type="password" placeholder="请确认密码" show-password>
              <template #prefix>
                <el-icon>
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="图形验证码">
            <el-input v-model="form.captcha" placeholder="请输入验证码"></el-input>
            <img :src="captchaImageURL" class="captcha-img" @click="refreshCaptcha" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onRegister" class="w-[250px]">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElNotification } from 'element-plus'

const router = useRouter()

// 设置全局的 Axios 配置，携带 Cookie
axios.defaults.withCredentials = true

const form = reactive({
  username: '',
  password: '',
  conpassword: '',
  captcha: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  conpassword: [{ required: true, message: '请确认密码', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

let storedSessionId = ''

const fetchCaptcha = async () => {
  try {
    const response = await axios.get('/api/users/generateImageCode', { responseType: 'blob' })   //响应类型为 blob  才可以使用URL.createObjectURL()
    // console.log(response)
    storedSessionId = response.headers["session-id"] // 从响应头中获取 Session ID
    console.log("session-id", storedSessionId)
    const imageUrl = URL.createObjectURL(response.data)
    return imageUrl // 返回创建的图片 URL
  } catch (error) {
    console.error('Error fetching captcha:', error)
  }
}

const captchaImageURL = ref()

onMounted(() => {
  refreshCaptcha()
})

const refreshCaptcha = async () => {
  captchaImageURL.value = await fetchCaptcha()
}

const formRef = ref(null)

const onRegister = () => {
  formRef.value!.validate(async (valid: boolean) => {
    if (!valid) {
      return false
    }

    const requestData = {
      username: form.username,
      password: form.password,
      conpassword: form.conpassword,
      captcha: form.captcha
    }
    try {
      const headers = {
        'Session-ID': storedSessionId // 将 sessionId 放入请求头中的 'Session-ID' 字段
      }
      const response = await axios.post(`/api/users/register`, requestData, { headers })
      console.log(response.data)
      ElNotification({
        message: "注册成功",
        type: 'success',
        duration: 3000
      })
      router.push("/login")
    } catch (error: any) {
      if (error.response) {
        ElNotification({
          message: error.response.data.msg || '请求失败',
          type: 'error',
          duration: 3000
        })
      } else {
        console.error('请求失败', error)
      }

    }
  })
}
</script>


<style scoped>
.label {
  width: 80px;
  text-align: right;
  margin-right: 20px;
}

.captcha-img {
  cursor: pointer;
  width: 100px;
}

.bg-fixed {
  background-image: url("@/assets/bg5.jpg");
  background-size: cover;
  background-attachment: fixed;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.register-container {
  @apply flex items-center justify-center flex-col;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.register-container .title {
  @apply text-light-50 font-bold text-5xl mb-4;
}

.box {
  width: 300px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  padding: 25px;
}
</style>